﻿using HSJM.Service.MWS.Core;
using HSJM.Service.MWS.Core.ShareMode;
using HSJM.Service.MWS.Domain.Entitys;
using HSJM.Service.MWS.Infrastructure;
using HSJM.Service.MWS.Infrastructure.Dapper;
using HSJM.Service.MWS.Utility.Logs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Dapper.SqlMapper;

namespace HSJM.Service.MWS.Domain.Domain.Base
{
    public class BaseDomain<T, TCondition> where T : class, IEntity
    {
        IRepository<T> _Repository { get; set; }
        public BaseDomain(IRepository<T> Repository)
        {
            this._Repository = Repository;
        }
        /// <summary>
        /// 获取事物
        /// </summary>
        /// <returns></returns>
        public IDbTransaction GetTransaction()
        {
            return _Repository.GetTransaction();
        }

        #region 查询
        /// <summary>
        /// 查询行数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetAsync(long id)
        {
            return await _Repository.GetAsync(id).ConfigureAwait(false);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T>> GetListAsync(object param = null, string sql = null, CommandType? commandType = null) { 
            return await _Repository.GetListAsync(param,sql, commandType).ConfigureAwait(false);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="param"></param>
        /// <param name="sql"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T>> GetListAsync(TCondition condition)
        {
            var sqlStr = TrunConditionToSql(condition);
            return await _Repository.GetListAsync(sqlStr).ConfigureAwait(false);
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public PagedResult<T> GetPageList(int pageIndex, int pageSize, string sql = null, object param = null)
        {
            var result = _Repository.GetPageList( pageIndex, pageSize, sql, param);
            return result;
        }
        #endregion

        #region 新增

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="list"></param>
        public async Task<HttpResponseResultModel<bool>> InsertBatch(List<T> list)
        {
            HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
            using (IDbTransaction transaction = _Repository.GetTransaction())
            {
                try
                {
                    foreach (var item in list)
                    {
                       var result=await _Repository.InsertAsync(item, transaction).ConfigureAwait(false);
                        if (result<0)
                        {
                            transaction.Rollback();
                            httpResponseResultModel.IsSuccess = false;
                            return httpResponseResultModel;
                        }
                    }
                    transaction.Commit();
                    httpResponseResultModel.IsSuccess = true;
                    httpResponseResultModel.BackResult = true;
                }
                catch (Exception ex)
                {
                    MyLogger.Logger.Error(ex.Message);
                    transaction.Rollback();
                    httpResponseResultModel.IsSuccess = false;
                    httpResponseResultModel.ErrorMessage = ex.Message;
                }
             
            }
            return httpResponseResultModel;
        }

        /// <summary>
        /// 添加行数据
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dbTransaction"></param>
        /// <returns></returns>
        public async Task<HttpResponseResultModel<bool>> InsertAsync(T entity, IDbTransaction dbTransaction = null)
        {
            HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
            try
            {
                var result = await _Repository.InsertAsync(entity, dbTransaction).ConfigureAwait(false);
                if (result < 0)
                {
                    httpResponseResultModel.ErrorMessage = "添加失败";
                    return httpResponseResultModel;
                }
                httpResponseResultModel.IsSuccess = true;
                httpResponseResultModel.BackResult = true;
            }
            catch (Exception ex)
            {
                httpResponseResultModel.IsSuccess = false;
                httpResponseResultModel.ErrorMessage= ex.Message;
            }
        
            return httpResponseResultModel;
        }
        #endregion

        #region 修改

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<HttpResponseResultModel<bool>> UpdateAsync(T entity,IDbTransaction dbTransaction = null)
        {
            HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
            try
            {
                var result = await _Repository.UpdateAsync(entity, dbTransaction).ConfigureAwait(false);
                if (!result)
                {
                    httpResponseResultModel.ErrorMessage = "修改失败";
                    return httpResponseResultModel;
                }
                httpResponseResultModel.IsSuccess = true;
                httpResponseResultModel.BackResult = true;
            }
            catch (Exception ex)
            {
                httpResponseResultModel.IsSuccess = false;
                httpResponseResultModel.ErrorMessage = ex.Message;
            }
       
            return httpResponseResultModel;
        }

        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="isDel">是否硬删除（默认软删除）</param>
        /// <param name="dbTransaction"></param>
        /// <returns></returns>
        public async Task<HttpResponseResultModel<bool>> DeleteAsync(T entity,bool isDel=false, IDbTransaction dbTransaction = null)
        {
            HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
            try
            {
                var result = await _Repository.DeleteAsync(entity, isDel, dbTransaction).ConfigureAwait(false);
                if (!result)
                {
                    httpResponseResultModel.ErrorMessage = "删除失败";
                    return httpResponseResultModel;
                }
                httpResponseResultModel.IsSuccess = true;
                httpResponseResultModel.BackResult = true;
            }
            catch (Exception ex)
            {
                httpResponseResultModel.IsSuccess = false;
                httpResponseResultModel.ErrorMessage = ex.Message;
            }
     
            return httpResponseResultModel;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<HttpResponseResultModel<bool>> DeleteBatch(List<T> list)
        {
            HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
            using (IDbTransaction transaction = _Repository.GetTransaction())
            {
                try
                {
                    foreach (var item in list)
                    {
                        var result=await  _Repository.DeleteAsync(item,dbTransaction: transaction).ConfigureAwait(false);
                        if (!result)
                        {
                            transaction.Rollback();
                            httpResponseResultModel.IsSuccess = false;
                            return httpResponseResultModel;
                        }
                    }
                    transaction.Commit();
                    httpResponseResultModel.IsSuccess = true;
                    httpResponseResultModel.BackResult = true;
                }
                catch (Exception ex)
                {
                    MyLogger.Logger.Error(ex.Message);
                    transaction.Rollback();
                    httpResponseResultModel.IsSuccess = false;
                    httpResponseResultModel.ErrorMessage = ex.Message;
                }
             
            }
            return httpResponseResultModel;
        }

        #endregion

        #region
        /// <summary>
        ///  sql拼接条件
        /// </summary>
        /// <param name="sqlStr"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public virtual string TrunConditionToSql(TCondition condition) {
            string sqlStr = "";
            foreach (var item in condition.GetType().GetProperties())
            {
                var val = item.GetValue(condition);
                if (val != null)
                {
                    sqlStr += $" AND {item.Name} = '{val}' ";
                }
            }
          
            return sqlStr;
        }
        #endregion
    }
}
